<template>
  <div class="center">
    <img src="../assets/background.png" alt="" class="img" />
    <div class="login">
      <img src="../assets/logos.png" alt="" class="logos" />
      <div class="tab-group">
        <div class="tab-item" :class="{ active: currentTab === 'code' }" @click="currentTab = 'code'">
          验证码登录
        </div>
        <div class="tab-item" :class="{ active: currentTab === 'password' }" @click="currentTab = 'password'">
          密码登录
        </div>
        <div class="tab-item" :class="{ active: currentTab === 'scan' }" @click="currentTab = 'scan'">
          扫码登录
        </div>
      </div>

      <!-- 登录表单 -->
      <div class="login-form">
        <div class="form-group" v-if="currentTab !== 'scan'">
          <div style="display: flex; flex-direction: column">
            <p>账号</p>
            <div class="input-group">
              <div class="country-code">
                <select>
                  <option value="+86 中国大陆" selected>+86</option>
                  <option value="+852 中国香港">+852</option>
                  <option value="+853 中国澳门">+853</option>
                  <option value="+886 中国台湾">+886</option>
                </select>
              </div>
              <input type="text" placeholder="请输入手机号" v-model="phoneNumber" />
            </div>
          </div>
        </div>

        <div class="form-group">
          <div style="display: flex; flex-direction: column;">
            <p v-if="currentTab !== 'scan'">{{ currentTab === 'code' ? '验证码' : '密码' }}</p>
            <div class="input-group code-group" :class="{
              'password-input': currentTab === 'password',
              'scan-input': currentTab === 'scan',
            }">
              <!-- 条件渲染：扫码登录时显示图片，否则显示输入框 -->
              <input v-if="currentTab !== 'scan'" :type="currentTab === 'password' ? 'password' : 'text'"
                placeholder="请输入验证码或密码" v-model="verificationCode" />
              <div v-else style="display: flex;flex-direction: column;align-items: center;">
                <img src="../assets/logo.png" alt="扫码登录" class="qr-code-image" />
                <p style="font-size: 10px;">打开【微信APP】扫一扫进行登录</p>
              </div>

              <button class="send-code-btn" v-if="currentTab === 'code'" @click="sendVerificationCode"
                :disabled="isSending || isCodeExpired">
                {{ sendButtonText }}
              </button>
            </div>
          </div>
        </div>

        <div class="form-group checkbox-group" v-if="currentTab !== 'scan'">
          <input type="checkbox" id="auto-login" v-model="autoLogin" />
          <label for="auto-login">7天自动登录</label>
        </div>

        <div class="form-group checkbox-group" style="margin-top: 40px" v-if="currentTab !== 'scan'">
          <input type="checkbox" id="agree" v-model="agreed" />
          <label for="agree">
            登录即代表同意
            <a href="#">《用户协议》</a> 和
            <a href="#">《隐私政策》</a>
          </label>
        </div>

        <button class="login-btn" @click="handleLogin">登录</button>
      </div>

    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
// 导入路由相关功能
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getsendSms, login, pwdLogin } from "@/api/login";


const router = useRouter(); // 创建路由实例
const currentTab = ref('code');
const phoneNumber = ref('');
const verificationCode = ref('');
const autoLogin = ref(false);
const agreed = ref(false);

// 验证码相关状态
const verificationCodeValue = ref(''); // 存储生成的验证码
const isSending = ref(false); // 是否正在发送验证码
const lastSendTime = ref(0); // 上次发送验证码的时间戳
const codeExpiresAt = ref(0); // 验证码过期时间戳
const isCodeExpired = ref(false); // 验证码是否过期

// 计算属性：发送按钮文本
const sendButtonText = ref('验证码');

// 手机号正则验证
function validatePhoneNumber(phone: string): boolean {
  // 中国大陆手机号正则：1开头，11位数字
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
}

// 发送验证码
const sendVerificationCode = () => {
  // 验证手机号
  if (!phoneNumber.value) {
    ElMessage({
      message: '请输入手机号',
      type: 'error'
    });
    return;
  }

  if (!validatePhoneNumber(phoneNumber.value)) {
    ElMessage({
      message: '请输入正确的手机号',
      type: 'error'
    });
    return;
  }

  // 联调短信
  getsendSms(phoneNumber.value)
    .then((res) => {
      console.log(phoneNumber.value);
      console.log('登录成功:', res);
      if (res.code === 200) {
        ElMessage({
          message: '发送成功',
          type: 'success'
        });
      }
    })
    .catch((err) => {
      console.error('验证码发送失败:', err);
    });


  // 检查是否在冷却期内
  const currentTime = Date.now();
  if (currentTime - lastSendTime.value < 60000) { // 1分钟内只能发送一次
    const remainingTime = Math.ceil((60000 - (currentTime - lastSendTime.value)) / 1000);
    alert(`请等待${remainingTime}秒后再试`);
    return;
  }

  // 生成6位随机验证码
  verificationCodeValue.value = Math.floor(100000 + Math.random() * 900000).toString();
  console.log('生成的验证码:', verificationCodeValue.value); // 控制台输出验证码

  // 更新发送状态
  isSending.value = true;
  lastSendTime.value = currentTime;
  codeExpiresAt.value = currentTime + 5 * 60 * 1000; // 5分钟后过期

  // 更新按钮文本
  sendButtonText.value = '60s';

  // 设置倒计时
  let countdown = 60;
  const countdownInterval = setInterval(() => {
    countdown--;
    if (countdown > 0) {
      sendButtonText.value = `${countdown}s`;
    } else {
      clearInterval(countdownInterval);
      isSending.value = false;
      // 检查验证码是否过期
      if (Date.now() < codeExpiresAt.value) {
        sendButtonText.value = '重新发送';
      } else {
        sendButtonText.value = '验证码已过期';
        isCodeExpired.value = true;
      }
    }
  }, 1000);
}

// 处理登录
function handleLogin() {
  if (!phoneNumber.value) {
    ElMessage({ message: '请输入手机号', type: 'error' });
    return;
  }

  if (!validatePhoneNumber(phoneNumber.value)) {
    ElMessage({ message: '请输入正确的手机号', type: 'error' });
    return;
  }

  if (currentTab.value === 'password') {
    if (!verificationCode.value) {
      ElMessage({ message: '请输入密码', type: 'error' });
      return;
    }

    if (!agreed.value) {
      ElMessage({ message: '请同意用户协议和隐私政策', type: 'error' });
      return;
    }

    //调用密码登录接口
    pwdLogin({
      phone: phoneNumber.value,
      password: verificationCode.value
    })
      .then((res) => {
        if (res.code === 200) {
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('phone', phoneNumber.value);
          localStorage.setItem("userPicture", res.data.userPicture);
          localStorage.setItem("userTel", res.data.userTel);
          localStorage.setItem("userId", res.data.id);
          if (localStorage.getItem('token')) {
            ElMessage({ message: '登录成功', type: 'success' });
            router.push('/Dashboard');
          } else {
            ElMessage({ message: '登录失败', type: 'error' });
          }

        } else {
          ElMessage({ message: res.msg || '登录失败', type: 'error' });
        }
      })
      .catch((err) => {
        console.error('密码登录失败:', err);
        ElMessage({ message: '登录失败，请稍后重试', type: 'error' });
      });

    return;
  }

  if (currentTab.value === 'code') {
    if (!verificationCode.value) {
      ElMessage({ message: '请输入验证码', type: 'error' });
      return;
    }

    if (Date.now() > codeExpiresAt.value) {
      ElMessage({ message: '验证码已过期，请重新获取', type: 'error' });
      return;
    }

    if (!agreed.value) {
      ElMessage({ message: '请同意用户协议和隐私政策', type: 'error' });
      return;
    }

    login({
      userTel: phoneNumber.value,
      verificationCode: verificationCode.value
    })
      .then((res) => {
        if (res.code === 200) {
          console.log(res);

          localStorage.setItem('token', res.data.token);
          localStorage.setItem('phone', phoneNumber.value);
          localStorage.setItem("userPicture", res.data.userPicture);
          localStorage.setItem("userTel", res.data.userTel);
          localStorage.setItem("userId", res.data.id);
          ElMessage({ message: '登录成功', type: 'success' });
          router.push('/Dashboard');
        } else {
          ElMessage({ message: res.msg || '登录失败', type: 'error' });
        }
      })
      .catch((err) => {
        console.error('验证码登录失败:', err);
        ElMessage({ message: '登录失败，请稍后重试', type: 'error' });
      });
  }

  // 扫码登录逻辑可后续扩展
}

// 生成随机token的函数
function generateToken(): string {
  // 生成一个随机的32位字符串作为token
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let token = '';
  for (let i = 0; i < 32; i++) {
    token += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return token;
}
</script>
<style scoped>
.center {
  width: 100%;
  height: 100vh;
  position: relative;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

.img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.login {
  box-sizing: border-box;
  position: absolute;
  background-color: rgb(13, 21, 32);
  right: 10vw;
  top: 20vh;
  color: white;
  width: 21vw;
  height: 65vh;
  border-top: 1px solid;
  border-image: linear-gradient(to right, blue, orange) 0.6;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logos {
  width: 75%;
  margin: 20px 0;
}

.tab-group {
  width: 80%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  border-bottom: 1px solid #2a3657;
  position: relative;
}

.tab-item {
  padding: 12px 0;
  font-size: 14px;
  color: #8a97b6;
  cursor: pointer;
  position: relative;
  text-align: center;
  flex: 1;
}

.tab-item.active {
  color: #ffffff;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409eff;
}

.login-form {
  width: 75%;
}

.form-group {
  font-size: 14px;
  margin-bottom: 8px;
}

.input-group {
  display: flex;
  align-items: center;
  background-color: rgb(31, 33, 37);
  border-radius: 8px;
  padding: 0 12px;

  height: 30px;
  width: 100%;
}

.country-code {
  width: 20%;
  position: relative;
}

.country-code::after {
  content: '';
  position: absolute;
  left: 30px;
  top: 50%;
  transform: translateY(-50%);
  border-width: 6px 5px 0 5px;
  border-style: solid;
  border-color: #8a97b6 transparent transparent transparent;
}

.input-group select {
  width: 100%;
  height: 100%;
  background-color: rgb(31, 33, 37);
  border: none;
  outline: none;
  color: #fff;
  appearance: none;
  font-size: 14px;
}

.input-group input {
  flex: 1;
  height: 100%;
  background-color: transparent;
  border: none;
  outline: none;
  color: #fff;
  font-size: 12px;
}

.code-group {
  display: flex;
  width: 100%;
  align-items: center;
}

.code-group input {
  flex: 1;
}

.send-code-btn {
  box-sizing: border-box;
  width: auto;
  padding: 0 10px;
  height: 100%;
  background-color: transparent;
  color: #409eff;
  border: none;
  border-left: 1px solid #364468;
  cursor: pointer;
  font-size: 10px;
  white-space: nowrap;
}

.send-code-btn:disabled {
  color: #8a97b6;
  cursor: not-allowed;
}

.checkbox-group {
  display: flex;
  align-items: center;
  font-size: 10px;
  color: #ccc;
}

.checkbox-group input {
  margin-right: 8px;
  width: 16px;
  height: 16px;
  appearance: none;
  background-color: transparent;
  border: 1px solid #409eff;
  border-radius: 2px;
  position: relative;
  cursor: pointer;
}

.checkbox-group input:checked::after {
  content: '';
  position: absolute;
  top: 1px;
  left: 5px;
  width: 3px;
  height: 8px;
  border: solid #409eff;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg) translate(-2px, -1px);
}

.checkbox-group a {
  color: #409eff;
  text-decoration: none;
}

.login-btn {
  position: absolute;
  bottom: 20px;
  width: 80%;
  height: 30px;
  background-color: #409eff;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.password-input {
  background-color: rgb(31, 33, 37);
  display: flex;
  justify-content: center;
  align-items: center;
}

.password-input input {
  color: black;
}

.scan-input {
  background-color: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qr-code-image {
  background-color: white;
  margin-top: 200px;
  width: 150px;
  height: 150px;
  object-fit: contain;
}
</style>